package com.example.wan1.view.home;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnPageChangeListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.wan1.R;
import com.example.wan1.adapter.ArticleListAdapter;
import com.example.wan1.adapter.BannerImageAdapter;
import com.example.wan1.base.fragment.SimpleFragment;
import com.example.wan1.bus.RxBus;
import com.example.wan1.constant.Constants;
import com.example.wan1.databinding.FragmentArticleBinding;
import com.example.wan1.event.CollectEvent;
import com.example.wan1.holder.BannerImageHolderView;
import com.example.wan1.model.ArticleBean;
import com.example.wan1.model.BannerBean;
import com.example.wan1.model.common.CommonResList;
import com.example.wan1.utils.AppUtils;
import com.example.wan1.utils.ToastUtils;
import com.example.wan1.utils.ToolsUtils;
import com.example.wan1.view.collect.HandleCollectTool;
import com.example.wan1.view.login.UserManager;
import com.example.wan1.view.web.JumpTool;
import com.scwang.smart.refresh.header.MaterialHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.indicator.CircleIndicator;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import butterknife.BindView;

/***
 * @Author: zxd
 * @CreateDate: 2020/6/28 14:14
 * @Description: 最新文章
 * 1.需要传进来一个参数判断是否需要进行banner的请求
 * 2.置顶文章和首页文章列表应该合到一起
 * 3.上拉加载更多和下拉刷新不能用？是不是没有初始化的问题
 *
 * 待做问题
 * 1.发现指示器的小圆点，使用shape比较好一点，使用图片不行。。补充：这里使用drawable资源最好
 * 2.最好弄一个自己封装的banner框架
 * 3.图片需要设置成带圆弧的,布局根本不需要设置圆弧，因为灰色的部分是rv的背景或者是banner tv的背景
 * 4.自己封装banner框架的时候，需要仔细观察，你裁剪的圆弧，在循环的时候，是从直角变成圆角的，这个点要注意
 *
 * 5.上拉和下拉是不需要加载的动画了。。。
 * 6.上拉时候刷新第一页，page应为1
 * 7.下拉时候page+1
 * 8.注意：加载更多的时候，是不需要添加mArticleList，否则会增加双倍 23 63 103 ...
 */
public class ArticleFragment extends SimpleFragment implements ArticleContract.View,
        OnLoadMoreListener, OnRefreshListener {

    private static String PARAM = "PARAM";
    private String type;//暂时没作用

    @BindView(R.id.srlheader)
    MaterialHeader mSrlheader;
    @BindView(R.id.article_rv)
    RecyclerView mArticleRv;
    @BindView(R.id.srl)
    SmartRefreshLayout mSrl;
    @BindView(R.id.article_container)
    RelativeLayout mArticleContainer;

    @Inject
    ArticlePresenter mPresenter;
    @Inject
    ArticleListAdapter mAdapter;
    @Inject
    List<ArticleBean> mArticleList;//文章列表

    //    private ConvenientBanner<BannerBean> mHomeBanner;
    private List<BannerBean> mBannerList;//轮播图的数据

    private int currentPage = 0;//当前页
    private Banner mBanner;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        type = getArguments().getString(PARAM, "");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //初始化数据
        //mArticleList = new ArrayList<>();
        mBannerList = new ArrayList<>();
    }

    @Override
    protected void initData() {
        //Log.i("zxd", "initData: ArticleFragment");
        showLoading();
        //请求数据
        mPresenter.start();
    }

    @Override
    protected void initView() {
        //这部分的逻辑放到父类中去实现了，除非子类这里有特殊要求，自己再修改即可
        //mSrlheader.setColorSchemeResources(R.color.qc_green);
        //停用
        //View view = fillRvHeader();

        //mAdapter = new ArticleListAdapter(R.layout.article_item, mArticleList);
        mArticleRv.setAdapter(mAdapter);
        mArticleRv.setLayoutManager(new LinearLayoutManager(mContext));
        //mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_RIGHT);

        /*DividerItemDecoration decor = new DividerItemDecoration(
                mContext, DividerItemDecoration.VERTICAL);
        decor.setDrawable(getResources().getDrawable(R.drawable.article_item_divider));
        mArticleRv.addItemDecoration(decor);*/

        mBanner = (Banner) LayoutInflater.from(mContext).inflate(R.layout.home_banner_new, mArticleContainer, false);
        mBanner.setAdapter(new BannerImageAdapter(mBannerList))
                .addBannerLifecycleObserver(this)//添加生命周期观察者
                .setIndicator(new CircleIndicator(mContext));
        mAdapter.addHeaderView(mBanner);

        mAdapter.setOnItemChildClickListener((baseQuickAdapter, view12, i) -> {
            switch (view12.getId()) {
                case R.id.article_iv_collect: {
                    if (!UserManager.getInstance().isLogin()) {
//                    if (!AppUtils.isLogin()) {
                        JumpTool.goLogin(getActivity());
                        return;
                    }
                    ArticleBean articleBean = mArticleList.get(i);
                    HandleCollectTool.getInstance().setInfo(articleBean, i, Constants.ARTICLE);
                    ImageView iv = view12.findViewById(R.id.article_iv_collect);
                    if (articleBean.isCollect()) {
                        HandleCollectTool.getInstance().cancelList();
                        iv.setImageResource(R.mipmap.heart_gray);
                    } else {
                        HandleCollectTool.getInstance().collectIn();
                        iv.setImageResource(R.mipmap.heart_red);
                    }
                }
                break;
            }
        });

        mSrl.setOnLoadMoreListener(this);
        mSrl.setOnRefreshListener(this);

        mSrl.setEnableRefresh(false);
        mSrl.setEnableLoadMore(false);

        mAdapter.setOnItemClickListener((baseQuickAdapter, view1, i) -> {
            JumpTool.goWeb(mContext, mArticleList.get(i).getTitle(), mArticleList.get(i).getLink());
            HandleCollectTool.getInstance().setInfo(mArticleList.get(i), i, Constants.ARTICLE);
        });

        mArticleRv.addOnScrollListener(mOnScrollListener);

        //处理颜色主题的banner选择的小点颜色
        if (ToolsUtils.getThemeColor(getActivity()) != 0) {
            mBanner.setIndicatorSelectedColor(ToolsUtils.getThemeColor(getActivity()));
        }
    }

    /***
     * 填充rv的头部
     * 因为存在切换图片的时候，图片会有一个变化，就是从直角变成圆角的过程，所以把下面的banner换成另外一个开源库
     */
    /*private View fillRvHeader() {
        //填充头部
        View view = LayoutInflater.from(mContext).inflate(R.layout.home_banner, mArticleContainer, false);
        mHomeBanner = (ConvenientBanner) view;
        mHomeBanner.setPages(new CBViewHolderCreator() {
            @Override
            public Holder createHolder(View itemView) {
                return new BannerImageHolderView(itemView, mContext);
            }

            @Override
            public int getLayoutId() {
                return R.layout.home_banner_item;
            }
        }, mBannerList)
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器，不需要圆点指示器可以不设
                .setPageIndicator(new int[]{R.drawable.indicator_normal, R.drawable.indicator_selected})
                //设置指示器的方向
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT)
                //设置指示器是否可见
                .setPointViewVisible(true)
                //监听翻页事件
                //.setOnPageChangeListener(this)
                //监听单击事件
                .setOnItemClickListener(position -> JumpTool.goWeb(mContext, mBannerList.get(position).getTitle(),
                        mBannerList.get(position).getUrl()));
        return view;
    }*/
    @Override
    protected int initLayoutRes() {
        return R.layout.fragment_article;
    }

    public ArticleFragment newInstance(String str) {
        ArticleFragment baseFragment = new ArticleFragment();
        Bundle bundle = new Bundle();
        bundle.putString(PARAM, str);
        baseFragment.setArguments(bundle);
        return baseFragment;
    }

    @Override
    public void onSuccess(CommonResList<ArticleBean> data) {
        mSrl.finishLoadMore(true);
        if (data.isOver()) {
            mAdapter.loadMoreEnd();//我是有底线的~
        }
        //currentPage 请求0返回1
        currentPage = data.getCurPage();
//        mArticleList.addAll(data.getDatas());//证明article不加，是正常的
        mAdapter.addData(data.getDatas());
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onSuccessBanner(List<BannerBean> data) {
        mBannerList.clear();
        mBannerList.addAll(data);
        //mHomeBanner.notifyDataSetChanged();
        mBanner.setDatas(mBannerList);
    }

    /***
     * 第一次进来加载
     * 1.mArticleList需要先清空，再加入加载的数据
     * 2.currentPage=1
     */
    @Override
    public void onSuccessArticle(List<ArticleBean> data) {
        hideLoading();
        currentPage = 1;
        if (mArticleList.size() != 0)
            mArticleList.clear();
        mArticleList.addAll(data);
        mAdapter.setNewData(mArticleList);

        if (mSrl == null) return;
        mSrl.setEnableRefresh(true);
        mSrl.setEnableLoadMore(true);
    }

    @Override
    public void onFailure(String msg) {
        showError();
        ToastUtils.showToast(msg);
        mSrl.setEnableLoadMore(false);
        mSrl.setEnableRefresh(false);
    }

    @Override
    public void onResume() {
        super.onResume();
//        mHomeBanner.startTurning(2000);//必须开启带时间否则不行
        mBanner.start();
    }

    @Override
    public void onPause() {
        super.onPause();
//        mHomeBanner.stopTurning();
        mBanner.stop();
    }

    /***
     * 上拉加载更多
     * @param refreshLayout
     */
    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        mArticleRv.postDelayed(() -> mPresenter.getArticleList(currentPage), 200);
    }

    /***
     * 下拉刷新
     * @param refreshLayout
     */
    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mArticleRv.postDelayed(() -> {
            mPresenter.refresh();
            mSrl.finishRefresh(true);
        }, 200);
    }

    public void notifyItemCollect() {
        if (mArticleRv.getAdapter() == null)
            mAdapter.bindToRecyclerView(mArticleRv);
        /*int pos = HandleCollectTool.getInstance().getPosition();
        Log.i("zxd", "notifyItemCollect: " + pos);
        ImageView iv = (ImageView) mAdapter.getViewByPosition(pos, R.id.article_iv_collect);
        Log.i("zxd", "notifyItemCollect: " + (iv == null));
        ArticleBean articleBean = HandleCollectTool.getInstance().getArticle();
        Log.i("zxd", "notifyItemCollect: " + articleBean.isCollect());
        if (articleBean.isCollect()) {
            iv.setImageResource(R.mipmap.heart_red);
        } else {
            iv.setImageResource(R.mipmap.heart_gray);
        }
        //        mAdapter.notifyItemChanged(pos);*/
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        RxBus.getDefault().subscribeSticky(mContext, new RxBus.Callback<CollectEvent>() {
            @Override
            public void onEvent(CollectEvent collectEvent) {
                if (Constants.ARTICLE.equals(collectEvent.getType()))
                    notifyItemCollect();
            }
        });
        RxBus.getDefault().subscribe(mContext, new RxBus.Callback<String>() {
            @Override
            public void onEvent(String s) {
                if (s.equals("cancelArticle")) {
                    mPresenter.refresh();
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unregister(mContext);
    }
}
